import logging
import snakemq.link as slink
import snakemq.packeter as spacketer
import snakemq.messaging as smessaging
import snakemq.message as smessage
import threading
import datetime
import json

# VitalsBuffer
# Records vital signs and persists them to
# a permanent storage device.
class VitalsBuffer(object):

	_id_prefix = "VITALB"

	def __init__(self, id, host="localhost"):
		self.id = self._id_prefix + "_" + str(id)
		self.host = host

		self.link = slink.Link()
		self.packeter = spacketer.Packeter(self.link)
		self.messaging = smessaging.Messaging(self.id, "", self.packeter)
		
		self.messaging.on_message_recv.add(self.recv)
		self.sensor_buffers = {}
		self.sensor_updates = {}

	# start listening on a port
	def addListener(self, port):
		print "Added listener on port %d." % port
		self.link.add_listener(("", port))

	# open outgoing channel on a port
	def addConnector(self, port):
		print "Added connector on port %d." % port
		self.link.add_connector((self.host, port))

	# message receipt callback
	def recv(self, conn, id, msg):
		message_data = json.loads(msg.data)
		# only acknowledge messages from a collector
		if id.startswith("COLLECTOR"):
			# register a collector with this buffer
			if message_data["command"] == "REGISTER":
				for sensor in message_data["sensors"]:
					self.sensor_buffers[sensor["name"]] = [sensor["level"]]
					self.sensor_updates[sensor["name"]] = datetime.datetime.now()
			# update the current levels in the buffer
			# TODO: logging, output to db
			if message_data["command"] == "UPDATE":
				for sensor in message_data["sensors"]:
					self.sensor_buffers[sensor["name"]].insert(0, sensor["level"])
					self.sensor_updates[sensor["name"]] = datetime.datetime.now()

	def start(self):
		threading.Thread(target=self.link.loop).start()